/**
 * File name:      AbstractBaseService.java
 * Date:           2013-3-25
 * Description:    // 用于详细说明此程序文件完成的主要功
 *                 // 能与其他模块或函数的接口，输出值、
 *                 // 取值范围、含义及参数间的关系
 * Modify History:     Date             Programmer       Notes
 *                    ---------        ---------------  ---------
 *                    2013-3-25            伍冲                              Initial
 **********************************************************************/
package com.wy.framework.services;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import com.opensymphony.xwork2.ActionContext;
import com.wy.framework.adapter.MessageSourceAdapter;
import com.wy.framework.constants.DBConstant;
import com.wy.framework.constants.FieldConstant;
import com.wy.framework.constants.RtnCodeConstant;
import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.dao.IDataBaseDao;
import com.wy.framework.exceptions.ServiceException;
import com.wy.framework.pojos.TSysConfig;
import com.wy.framework.pojos.TSysDbRouter;
import com.wy.framework.pojos.TSysUserinfo;
import com.wy.component.dataConvert.PropertyCopyUtil;
import com.wy.component.redis.RedisUtil;

/**
 * Created on 2013-3-25
 * <p>
 * Title: [服务层抽象基类]
 * </p>
 * <p>
 * Description: [服务层抽象基类]
 * </p>
 * 
 * @version 1.0
 */
public abstract class AbstractBaseService {
	
	public static Logger logger = LoggerFactory.getLogger(AbstractBaseService.class);
	
	@Autowired
	protected MessageSourceAdapter msgSourceAdapter;

	@Autowired
	protected IDataBaseDao dataBaseDao;

	public Object getSession(String key) {
		ActionContext ctx = ActionContext.getContext();
		return ctx.getSession().get(key);
	}
	public JdbcTemplate getJtByIpSegment(String ips) {
		JdbcTemplate jdbcTemplate = dataBaseDao.getJdbcTemplateDistributeByIpSegment(ips);
		if(jdbcTemplate==null){
			// 取得门店数据源
			List list = getDataBaseDao().getHibernateTemplate().find(" from TSysDbRouter r where r.ipSegment like '%"+ips+"%' ");
			if(list==null || list.size()==0){
				return null;
			}
			TSysDbRouter tSysDbRouter = (TSysDbRouter) list.get(0);
			//同时存jt到工厂
			jdbcTemplate = getDataBaseDao().getJdbcTemplateDistribute(tSysDbRouter);
		}
		return jdbcTemplate;
	}
	
	public TSysUserinfo loginUser() throws ErrorSqlException{
		String token = ServletActionContext.getRequest().getParameter("token");
		if(StringUtils.isEmpty(token))
			return null;
		String userId = RedisUtil.getUserId(token);
		TSysUserinfo t = (TSysUserinfo) dataBaseDao.load(TSysUserinfo.class, userId);
		String deptName = RedisUtil.getUserId(token+"-dept");
		logger.info("deptName : "+deptName);
		t.setDept(deptName);
		t.setDeptName(deptName);
		return t;
	}
	
	/**
	 * Function Name calendarMinus
	 * 
	 * @return IDataBaseDao
	 * @description //获取数据库操纵组件 Modification History //伍冲 2013-03-25 created
	 */
	public IDataBaseDao getDataBaseDao() {
		return dataBaseDao;
	}

	/**
	 * 
	 * <b>方法描述:</b><br>
	 * <font color="blue">把源对象属性值 拷贝至 目标对象 相匹配的
	 * 属性中去，源对象和目标对象可以是JavaBean、Map实现类（如HashMap、Hashtable、Properties等）。</font><br>
	 * <b>适用范围：</b><br>
	 * 1，JavaBean对象属性值拷贝至Map（HashMap、Hashtable、Properties等）类型中;<br>
	 * 2，JavaBean对象属性值拷贝至另一个JavaBean中; <br>
	 * 3，Map（HashMap、Hashtable、Properties等）类型对象属性值拷贝至一个JavaBean中;<br>
	 * 4，Map（HashMap、Hashtable、Properties等）类型对象属性值拷贝至一个Map类型对象中;<br>
	 * 
	 * @param: Object srcObject --源对象
	 * @param: Object targetObject --目标对象
	 * @param: String[] ignoreProperties --忽略拷贝的属性（如果不想拷贝某些属性，可以传入属性名称数组）
	 * @return: target Object
	 */
	protected Object CopyProperties(Object srcObject, Object targetObject,
			String[] ignoreProperties) {
		return PropertyCopyUtil.CopyProperties(srcObject, targetObject,
				ignoreProperties);
	}

	/**
	 * @param dataBaseDao
	 *            the dataBaseDao to set
	 */
	public void setDataBaseDao(IDataBaseDao dataBaseDao) {
		this.dataBaseDao = dataBaseDao;
	}

	/**
	 * 根据主键检查是否重复
	 * eg. existCheck(TcSysUserInfo.class, "D0001")				               
	*/
	public boolean existCheck(Class classType, Serializable pk)
			throws ServiceException {
		try {
			Object obj = dataBaseDao.load(classType, pk);
			if(obj != null){
				dataBaseDao.getHibernateTemplate().clear();
			}
			return obj != null;
		} catch (ErrorSqlException e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * Function Name querySysConfigById
	 * 
	 * @param //参数1说明
	 * @param //参数2说明
	 * @return TcSysConfig
	 * @description //函数功能、性能等的描述 Modification History //修改历史说明
	 */
	public String querySysConfigById(String configKey) throws ServiceException {
		String rspCode = null;
		String rspMsg = null;
		TSysConfig sysConfig = null;
		try {
			sysConfig = (TSysConfig) this.getDataBaseDao().load(TSysConfig.class, configKey);

			if (null == sysConfig
					|| sysConfig.getIsAvailable().equals(
							DBConstant.DB_STATUS_DISABLCE)) {
				rspCode = RtnCodeConstant.RTN_CODE_SEARCH_RESULT_EMPTY;
				rspMsg = msgSourceAdapter.getMessage(rspCode);
				throw new ServiceException(rspCode, rspMsg);
			}

		} catch (ErrorSqlException e) {
			e.printStackTrace();
			rspCode = RtnCodeConstant.RTN_CODE_UNKNOW_ERROR;
			rspMsg = msgSourceAdapter.getMessage(rspCode);
			throw new ServiceException(rspCode, rspMsg, e);
		}
		return sysConfig.getConfigValue();
	}
	
}
